<?php

class SubjectsController extends AppController {

    var $name = 'Subjects';
    var $response = array();                                                      //variable to return response.
    var $components = array('RequestHandler', 'Access');
    var $paginate = array(
        'limit' => '30',
        'order' => array('Subject.subject' => 'desc')
    );
    var $uses = array('Tag', 'Adjective', 'Subject', 'Credit', 'UserCredit', 'FlaggedSubject', 'Page', 'Pageredirect', 'SubjectRate', 'User', 'ProfileFieldValue', 'ProfileField');

    function beforeFilter() {
        $this->Auth->loginRedirect = array('controller' => 'Dashboard', 'action' => 'index');
        $this->Auth->allow('login_element', 'subject', 'rate', 'synonyms', 'get_suggestion', 'get_redirects', 'adjectives', 'generatepopupimage', 'add', 'subject_list', 'search');
    }

    function admin_index() {

        if (!$this->Access->check('Subject', 'read')) {
            $this->Session->setFlash(__("You don't have permissions to View this content"));
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (isset($this->params['named']['status'])) {
            $this->paginate = array(
                'limit' => '20',
                'order' => array('Subject.created' => 'desc'),
                'conditions' => array('Subject.status' => $this->params['named']['status'])
            );
        }
        $data = $this->paginate('Subject');
        $adjectives = '';
        $taglist = '';
        $i = 0;

        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */

        foreach ($data as $value) {
            $adj_ids = Set::classicExtract($value['SubjectAdjectives'], '{n}.adjective_id');

            //$adj_ids = implode(',', $result);debug($adj_ids);
            $tag_ids = explode(',', $value['Subject']['tag_ids']);                

            /*             * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
            foreach ($adj_ids as $id) {
                $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $id)));
                $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
            }


            /*             * ************** 
             * This loop will get all the formated tags for a particular record.
             *  Functions used : 
             *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
             *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
             * 
             * *************** */
            foreach ($tag_ids as $tid) {
                if(empty($tid))
                    continue;
                $tag_arr = $this->get_parent_list($tid);
                $taglist = $this->formated_tags($tag_arr, '>');
            }
            $data[$i]['Subject']['adjective_ids'] = substr($adjectives, 1);
            $data[$i]['Subject']['tag_ids'] = $taglist;
            $i++;
            $adjectives = '';
            //$tags='';
        }

        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('Subjects', $data);
    }

    function admin_approve($id = null) {
        if (!$this->Access->check('User', 'read')) {
            $this->Session->setFlash('You dont have permissions to View this content');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!empty($id) || isset($this->data)) {

            if (empty($this->data)) {
                $data = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id, 'Subject.status =' => '0'), 'recursive' => '2'));
                if (!$data) {
                    $this->Session->setFlash('Subject Already approved.Cant approve again ');
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
                }
                $this->admin_edit($id);
                $credits = $this->Credit->find('all');
                $urating = $this->Subject->query("SELECT subject_rates.rating, user_id FROM `subject_rates` where subject_id='$id'");
                $this->set('credits', $credits);
            } else {
                $redirect = true;                             //We will set $redirect to true so that admin_edit does not redirect as we want the control back for further process 
                $this->admin_edit($this->data, $redirect);
                $this->saveCredit($this->data);
                $update = mysql_query("Update `subject` set status='1',`approved_by`='" . $_SESSION['Auth']['User']['id'] . "',`approved_on`=NOW() where subject.id='" . $this->data['Subject']['id'] . "'");
                $this->Session->setFlash('Subject Approved.');

                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));


                //debug($this->data);
            }
        } else {
            $this->Session->setFlash('Subject not available ');
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
    }

    function admin_add() {
        if (!$this->Access->check('Subject', 'create')) {
            $this->Session->setFlash("You can't add new subjects");
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (isset($this->data)) {

            $tags = array();

            if (isset($_POST['tag_ids'])) {
                $tags = $_POST['tag_ids'];
            }
            $uniquetags = array_unique($tags);

            $tag_ids = implode(',', $uniquetags);
            $tag_ids = ltrim($tag_ids, ',');
			if(!empty($tag_ids))
				$tag_ids = ','.$tag_ids.',';
            $this->data['Subject']['tag_ids'] = $tag_ids;

            if ($this->data['Subject']['image']['error'] == '0') {
                $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                if ($this->check_image_extension($ext['extension'])) {
                    $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                    if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                        move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                    }
                    $this->data['Subject']['image'] = $image_name;
                } else {
                    $this->data['Subject']['image'] = '';
                }
            } else {
                $this->data['Subject']['image'] = '';
            }
            $this->data['Subject']['user_id'] = $_SESSION['Auth']['User']['id'];
            $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);

            //$this->data=$this->set_adjective_array($this->data);
            if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {

                $this->admin_save_adjectives($this->data['Subject']['adjective_ids'], $this->Subject->id);
                $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];
                $this->Subject->SubjectRate->save($this->data, array('validate' => 'only'));
                $this->Session->setFlash('Subject Saved');
                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));
            }
        }
    }

    function admin_save_adjectives($adjective_ids, $subject_id) {

        if ($adjective_ids) {
            $adjective_ids = explode(',', $adjective_ids);
            foreach ($adjective_ids as $adjective):
                $save_adjective = mysql_query("INSERT into `subject_adjectives` (`adjective_id`,`subject_id`,`user_id`,`created`) 
                    VALUES('" . $adjective . "','" . $subject_id . "','" . $_SESSION['Auth']['User']['id'] . "',NOW())");
            endforeach;
            return true;
        }
        return false;
    }

    function admin_edit($id = null, $redirect = null) {                      //We have introduced second argument to override the default redirect on successfull save. When set to true this method will not redirect.
        if (!$this->Access->check('Subject', 'update')) {
            $this->Session->setFlash('Permission denied. Please contact your Administrator for more permissions');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if ($id) {
            if (empty($this->data)) {

                $this->data = $this->Subject->read(null, $id);
                $this->data['adjective_ids'] = '';
                if (!$this->data) {
                    $this->Session->setFlash('Subject not available ');
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '1'));
                } else {
                    $subjecttitle = json_encode(array('0' => array('id' => $this->data['Subject']['subject'], 'name' => $this->data['Subject']['subject'])));
                    $this->set('subjecttitle', $subjecttitle);
                    if (($this->Access->check('User', 'update')) || ($this->data['Subject']['user_id'] == $_SESSION['Auth']['User']['id'] && $this->data['Subject']['status'] == '0')) {
                        $tags = array();
                        if (!empty($this->data['SubjectAdjectives'])) {
                            $adjective_ids = Set::classicExtract($this->data['SubjectAdjectives'], '{n}.adjective_id');
                            $subject_adjective_ids = Set::classicExtract($this->data['SubjectAdjectives'], '{n}.id');
                            $this->data['adjective_ids'] = implode(',', $subject_adjective_ids);
                            $adjective_ids = array_combine($subject_adjective_ids, $adjective_ids);
                            $adjectivelist = $this->adjectivelist($adjective_ids);
                            $this->set('adjectivelist', $adjectivelist);
                        }
                        $tag_ids = explode(',', $this->data['Subject']['tag_ids']);
                        foreach ($tag_ids as $tid) {
							if(empty($tid))
								continue;
                            $tag_arr = $this->get_parent_list($tid);
                            $taglist = $this->formated_tags($tag_arr, '>');
                            $tag_arr = array('tag_id' => $tid, 'tag' => $taglist);
                            array_push($tags, $tag_arr);
                        }

                        $this->data['Subject']['taglist'] = $tags;

                        $this->set('id', $id);
                        /*                         * *****Prepopulate Adjective list******** */
                    } else {
                        $this->Session->setFlash('You can only Edit your own submitted Subjects');
                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => '0'));
                    }
                }
            } else {
                //debug($this->data);
                $this->data['Subject']['old_adjectives'] = explode(',', $this->data['Subject']['old_adjectives']);

                $this->data['Subject']['adjective_ids'] = explode(',', $this->data['Subject']['adjective_ids']);
                if (!empty($this->data['Subject']['old_adjectives']['0'])) {

                    foreach ($this->data['Subject']['old_adjectives'] as $old_adjectives):
                        //echo $old_adjectives;
                        if (!in_array($old_adjectives, $this->data['Subject']['adjective_ids'])) {
                            $delete_adjective = mysql_query("DELETE FROM `subject_adjectives` WHERE `id`='" . $old_adjectives . "'");

                            // echo "<br>";
                        }
                    //echo "<br>";
                    endforeach;
                    //die('dsda');
                } else {
                    //die('else');

                    $adjective_id = explode(',', $this->data['Subject']['adjective_ids']);

                    if (count($adjective_id) > 0) {
                        foreach ($adjective_id as $id) {
                            $add_new_adjective = mysql_query("INSERT INTO `subject_adjectives` (`adjective_id`,`user_id`,`subject_id`,`created`) VALUES ('" . $id . "','" . $this->Auth->User('id') . "','" . $this->data['Subject']['id'] . "',NOW())");
                        }
                    }
                }
                $tag_ids = null;
                $this->Subject->id = $this->data['Subject']['id'];
                if (isset($_POST['tag_ids'])) {
                    $tags = $_POST['tag_ids'];
                    //if(!empty($_POST['data']['Subject']['tag_ids'])){array_push($tags, $_POST['data']['Subject']['tag_ids']);}
                    $uniquetags = array_unique($tags);
                    //debug($uniquetags);die();
                    $tag_ids = implode(',', $uniquetags);
                    $tag_ids = ltrim($tag_ids, ',');
					if(!empty($tag_ids))
						$tag_ids = ','.$tag_ids.',';
                }
                $this->data['Subject']['tag_ids'] = $tag_ids;

//debug($tag_ids);debug($uniquetags);die();  
                if (isset($this->data['Subject']['image'])) {
                    if ($this->data['Subject']['image']['error'] != '0') {
                        $this->data['Subject']['image'] = '';
                    } else {
                        $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                        if ($this->check_image_extension($ext['extension'])) {
                            $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                            $filename = WWW_ROOT . 'img/uploads/Subjects/' . $image_name;
                            if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                                move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                            }

                            /*   if ($this->Subject->validates(array('fieldlist' => array('image')))) {
                              if (!is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {

                              mkdir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject']);

                              chmod(WWW_ROOT . 'img/uploads/Subjects/'. $this->data['Subject']['subject'],'0777');
                              $path = WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'];
                              } elseif (is_dir(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'])) {
                              if (!empty($this->data['Subject']['image'])) {

                              move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['subject'] . '/' . $this->data['Subject']['image']['name']);
                              } else {
                              $this->Session->setFlash('Somthing went wrong uploading image');
                              }
                              }
                              } */
                            $this->data['Subject']['image'] = $image_name;
                        } else {
                            $this->data['Subject']['image'] = null;
                        }
                    }
                }
                $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);  // Convert specifier to lowercase
                if (isset($_POST['rating_id'])) {
                    if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {
                        $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                        $this->data['SubjectRate']['id'] = $_POST['rating_id'];
                        $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                        $this->data['SubjectRate']['rating'] = $_POST['rating'];
                        $this->Subject->SubjectRate->save($this->data);
                        $this->Session->setFlash('Subject Saved');

                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->data['Subject']['status']));
                    }
                } else {
					unset($this->data['Subject']['old_adjectives']);
					unset($this->data['Subject']['adjective_ids']);
                    $this->Subject->set($this->data);
                    //debug($this->data);die();					
                    $r = $this->Subject->save($this->data, array('validate' => false));//dont validate on edit
					
					//debug($this->data);die();

                    if (!$redirect) {
                        $this->Session->setFlash('Subject Updated ');
                        $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->data['Subject']['status']));
                    }
                }
            }
        } else {
            $this->Session->setFlash('Subject not available ');
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
    }

    /*     * *************** This function is used in admin_edit to set Adjective ids for edit page******************** */

    function adjectivelist($adjective_ids) {
        $i = 0;
        foreach ($adjective_ids as $key => $id) {
            $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id' => $id), 'fields' => array('Adjective.id', 'Adjective.title')));
            $adjectives[$i]['id'] = $key;
            $adjectives[$i]['name'] = $adj['Adjective']['title'];
            $i++;
        }

        //$adjectivelist = substr($adjectives, 1);
        return $adjectives;
    }

    function admin_view($id = null) {

        $adjectives = '';
        $taglist = '';
        $tags = array();
        $i = 0;
        $data = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id)), array('resursive' => '2'));


        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */
        $adj_ids = array_unique(Set::classicExtract($data['SubjectAdjectives'], '{n}.adjective_id'));

        $tag_ids = explode(',', @$data['Subject']['tag_ids']);

        /*         * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */

        foreach ($adj_ids as $aid) {
            $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $aid)));
            $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
        }


        /*         * ************** 
         * This loop will get all the formated tags for a particular record.
         *  Functions used : 
         *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
         *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
         * 
         * *************** */
        foreach ($tag_ids as $tid) {
			if(empty($tid))
				continue;
            $tag_arr = $this->get_parent_list($tid);
            $taglist = $this->formated_tags($tag_arr, '>');
            $tag_arr = array('tag_id' => $tid, 'tag' => $taglist);
            array_push($tags, $tag_arr);
        }
        $data['Subject']['adjective_ids'] = substr($adjectives, 1);
        $data['Subject']['tag_ids'] = $tags;
        $i++;
        $adjectives = '';
        $tags = array();


        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('subjects', $data);
        $related_subjects = $this->get_related_subjects($data['Subject']['subject']);
        $this->set('related_subjects', $related_subjects);
        $lastRated = $this->Subject->SubjectRate->find('first', array(
            'conditions' => array(
                'SubjectRate.subject_id' => $id,
                'SubjectRate.user_id' => $_SESSION['Auth']['User']['id']
            ),
            'order' => 'SubjectRate.created desc',
            'limit' => '1'
                )
        );
        $this->set('lastrated', $lastRated);
    }

    function admin_delete($id = null) {
        if (!$this->Access->check('Subject', 'delete')) {
            $this->Session->setFlash('Permission denied. Please contact your Administrator for more permissions');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!$id) {
            $this->Session->setFlash("Invalid Link");
            $this->redirect(array('controller' => 'Subjects', 'action' => 'index'));
        }
        $subject = $this->Subject->find('first', array('conditions' => array('Subject.id =' => $id)));
        //debug($categorydata);die();//$foldername=$categorydata['']
        if (!empty($subject)) {
            $dir = WWW_ROOT . 'img/uploads/Subjects/' . $subject['Subject']['image'];
            if ($this->Subject->delete($id)) {
                $file = new File($dir);
                $file->delete();
                $this->Session->setFlash("Subject deleted");
                $this->redirect(array('controller' => 'Subjects', 'action' => 'index', 'status' => $this->params['named']['status']));
            }
        } else { /*         * ******* In case category not found.Redirect with error message ***** */
            $this->Session->setFlash('Subject Not found.');
            $this->redirect(array('controller' => 'Subject', 'action' => 'index', 'status' => $this->params['named']['status']));
        }
    }

    function admin_flagged() {
        $this->paginate = array('limit' => '10');

        $data = $this->paginate('FlaggedSubject');

        $this->set('subjects', $data);
    }

    function admin_delete_flagged($id = null) {
        if ($id) {
            if ($this->FlaggedSubject->delete($id)) {
                $this->Session->setFlash('Successfully deleted');
                $this->redirect(array('action' => 'admin_flagged'));
            }
        } else {
            $this->redirect(array('controller' => 'Subejcts', 'action' => 'admin_flagged'));
        }
    }

    function rate() {

        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', -1);
            $this->autoRender = false;
            $adjective_ids = array();
            $new_adj = array();
            if (isset($_POST['subject_id'])) {
                // print_r($this->Auth);
                $response = array('error' => false, 'login' => true, 'canRate' => true, 'subjectID' => '0');
                if ($this->Auth->User('id')) {
                    $this->data['SubjectRate']['subject_id'] = $_POST['subject_id'];
                    $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                    $this->data['SubjectRate']['rating'] = $_POST['rating'];
                    $check = $this->rate_time($this->data['SubjectRate']['subject_id'], $this->data['SubjectRate']['user_id']);
                    if ($check == '0') {
                        if (isset($_POST['adj1'])) {
                            if (!is_numeric($_POST['adj1'])) {
                                $new_adj[] = $_POST['adj1'];
                            } else {
                                $adjective_ids[] = $_POST['adj1'];
                            }
                        }
                        if (isset($_POST['adj2'])) {
                            if (!is_numeric($_POST['adj2'])) {
                                $new_adj[] = $_POST['adj2'];
                            } else {
                                $adjective_ids[] = $_POST['adj2'];
                            }
                        }
                        if ($_POST['adj3']) {
                            if (!is_numeric($_POST['adj3'])) {
                                $new_adj[] = $_POST['adj3'];
                            } else {
                                $adjective_ids[] = $_POST['adj3'];
                            }
                        }

                        if ($this->Subject->SubjectRate->save($this->data)) {
                            $data = mysql_query("SELECT MAX(balance) as balance FROM user_credits where user_id='" . $this->data['SubjectRate']['user_id'] . "'");
                            $row = mysql_fetch_array($data);
                            $sql = mysql_query("INSERT into user_credits (`subject_id`,`credit_id`,`user_id`,`credit`,`balance`,`created`)
                                         VALUES('" . $this->data['SubjectRate']['subject_id'] . "','1','" . $this->data['SubjectRate']['user_id'] . "','1','" . ($row['balance'] + 1) . "',NOW())");
                            if (count($new_adj) > 0) {
                                foreach ($new_adj as $adj):
                                    $query = mysql_query("INSERT INTO `suggested_adjectives` (`title`,`user_id`,`subject_id`,`created`,`modified`,`status`)
                            VALUES ('" . ucfirst($adj) . "','" . $this->data['SubjectRate']['user_id'] . "','" . $this->data['SubjectRate']['subject_id'] . "',NOW(),NOW(),'1')");
                                endforeach;
                            }
                            if (count($adjective_ids) > 0) {
                                foreach ($adjective_ids as $adj):
                                    $query = mysql_query("INSERT INTO `subject_adjectives` (`adjective_id`,`user_id`,`subject_id`,`created`,`status`)
                            VALUES ('" . $adj . "','" . $this->data['SubjectRate']['user_id'] . "','" . $this->data['SubjectRate']['subject_id'] . "',NOW(),'0')");
                                endforeach;
                            }
                            $this->Session->setFlash('Thank you for rating the subject');
                            $response['error'] = false;
                            $response['subjectID'] = $this->data['SubjectRate']['subject_id'];
                            //echo $this->base.'/Subjects/subject/'.$this->data['SubjectRate']['subject_id'];
                        }
                    }else {
                        $response['error'] = true;
                        $response['canRate'] = false;
                        //echo "You Can't rate a Subject within seven days.";
                    }
                } else {
                    $response['error'] = true;
                    $response['login'] = false;

                    //              echo "Login First";
                }


                print_r(json_encode($response));
            }
        }
    }

    function admin_rate() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);

            $this->autoRender = false;
            if (isset($_POST['id'])) {
                $this->data['SubjectRate']['subject_id'] = $_POST['id'];
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];

                if ($this->Subject->SubjectRate->save($this->data)) {
                    $data = mysql_query("SELECT MAX(balance) as balance FROM user_credits where user_id='" . $_SESSION['Auth']['User']['id'] . "'");
                    $row = mysql_fetch_array($data);
                    $sql = mysql_query("INSERT into user_credits (`subject_id`,`credit_id`,`user_id`,`credit`,`balance`,`created`)
                                         VALUES('" . $_POST['id'] . "','1','" . $_SESSION['Auth']['User']['id'] . "','1','" . ($row['balance'] + 1) . "',NOW())");
                    $this->Session->setFlash('Thanks for rating');
                }
            }
        }
    }

    /*     * ****************************************************************   Custom Functions Starts           *********************************************************** */

    /*     * **************** This function will return the adjectives to add and edit VIEWS. To be called from autocomplete widget *********************** */

    function admin_adjectives() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $adjectives = $this->Adjective->find('all', array('conditions' => array('Adjective.title LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
            $i = 0;
            foreach ($adjectives as $adjective) {
                $response[$i]['id'] = $adjective['Adjective']['id'];
                $response[$i]['name'] = "" . $adjective['Adjective']['title'] . "";
                $i++;
            }
            if (isset($_GET["callback"])) {
                $response = $_GET["callback"] . "(" . $response . ")";
            }

            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************************** Adjective function ends  *********************************** */


    /*     * **************** This function will return the adjectives for front end withh option to suggest. To be called from autocomplete widget *********************** */

    function subject($id = null,$show_thanks = null) {
        //Configure::write('debug', 0);
        
        /*         * */
        if (!empty($this->params['id'])) {
            $sub = $this->Subject->find('first', array('conditions' => array('Subject.subject' => $this->params['id'])));
            $id = $sub['Subject']['id'];
        }
        /*         * * */
        
        if ($id) {
            //debug($this->Auth->User('above_17'));

            $subject = $this->Subject->find('first', array('conditions' => array('Subject.id' => $id, 'Subject.status' => '1')));
            if ($subject) {
                if ($subject['Subject']['17+'] == '1') {


                    if (!$this->Auth->User('id')) {
                        $this->Session->setFlash('Login to View this subject');
                        $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
                    }

                    $user_data = mysql_query("SELECT dob from user_profiles where user_id='" . $this->Auth->User('id') . "'") or die(mysql_error());
                    $result = mysql_fetch_assoc($user_data);

                    if (!empty($result['dob'])) {

                        $date1 = new DateTime($result['dob']);
                        $date2 = new DateTime(date('Y-m-d'));
                        $interval = $date1->diff($date2);
                        //echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; die();
                        if ($interval->y <= '17') {
                            $this->Session->setFlash('You cant View This subject');
                            $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
                        }
                    } else {
                        $this->Session->setFlash('This Subject is for 17+. Provide your age to view this Subject');
                        $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
                    }
                    //debug($this->Auth->User('above_17'));
                }
                /*                 * ********* Find Current Users rating for the subject********** */
//            foreach ($subject['SubjectRate'] as $rating) {
//                if($this->Auth->User('id')){
//                if ($rating['user_id'] == $_SESSION['Auth']['User']['id']) {
//                    $subject['Subject']['urated'] = $rating['rating'];
//                    break;
//                }
//                }
//            }
                if ($this->Auth->User('id')) {

                    if ($this->rate_time($id, $this->Auth->User('id')) > '0') {
                        $subject['Subject']['can_rate'] = false;
                    } else {
                        $subject['Subject']['can_rate'] = true;
                    }
                    $subject['Subject']['if_rated'] = $this->SubjectRate->find('count', array('conditions' => array('SubjectRate.subject_id' => $id, 'SubjectRate.user_id' => $this->Auth->User('id'))));
                } else {
                    $subject['Subject']['can_rate'] = true;
                    $subject['Subject']['if_rated'] = '0';
                }


                /*                 * **********find average rating of subject******** */

                $result = Set::classicExtract($subject, 'SubjectRate.{n}.rating');
                $subject['Subject']['avg_rating'] = array_sum($result) / count($result);

                /*                 * ******Average Rating Ends ***** */

                /*                 * ***************************** */
                if (count($subject['SubjectAdjectives']) > 0) {
                    $this->set('topadjectives', $this->top_adjectives($subject));
                }
                /*                 * ***************************** */

//                $history = $this->Subject->SubjectRate->find('all', array('conditions' => array('SubjectRate.subject_id' => $id), 'order' => array('SubjectRate.created asc'), 'fields' => array('AVG(SubjectRate.rating) AS rating', 'SubjectRate.created'), 'group' => array('DATE(SubjectRate.created)')));
//                 debug($history);die();
//                $output = '[';
//                $output_array = array();
//                $i = 0;
//                foreach ($history as $data):$i++;
//                    $output_array[$i] = "['" . $data['SubjectRate']['created'] . "'," . round($data['0']['rating'], 2) . "]";
//                endforeach;
//                $output_data = implode(',', $output_array);
//                $output = '[' . $output_data . ']';
//                $this->set('history', $output);
//               

                $this->set('history', $this->history_graph($id));

                $this->set('subject', $subject);
                $taglist = $this->get_taglist($subject['Subject']['tag_ids']);
                $this->set('tags', $taglist);
                $this->Subject->User->unbindModel(array('hasMany' => array('UserCredit', 'Subject', 'SubjectRate')));
                $find_creator_info = $this->Subject->User->find('first', array('conditions' => array('User.id' => $subject['Subject']['user_id']), 'fields' => array('User.username', 'User.email', 'UserProfile.screenname', 'UserProfile.image')));
                $this->set('creator', $find_creator_info);

                /*                 * ****************** Meter Content   ********************** */
//           
//           $randomSubjectIds = $this->Subject->find('list', array('conditions'=>array('Subject.image !='=>'','Subject.17+'=>'0','Subject.status'=>'1'),'fields' => 'id','order' => 'RAND()','limit' => 50));
//           $subjects = $this->Subject->find('all', array('contain' => array('Subject.subject','Subject.desc','Subject.id','Subject.image'),
//                                                         'conditions' => array('Subject.id' => $randomSubjectIds,'Subject.image <>'=>''),
//                                                         'order' => 'RAND()'));
//    



                $id_list = array();
                $ids = set::classicExtract($taglist, '{n}.{n}.id');

                $idy = array();
                foreach ($ids as $array) {
                    foreach ($array as $id) {
                        $idy[] = $id;
                    }
                }
                $unique_ids = array_unique($idy);
                $list = implode('|', $unique_ids);

                $this->Subject->unbindModel(array('hasMany' => array('SubjectRate', 'Attribute', 'Subjectredirect', 'SubjectAdjectives', 'Comment'), 'belongsTo' => array('User')));
                /*
                  if (isset($_SESSION['above_17']) && (!$_SESSION['above_17'])) {    // Check if user can see 17+ subject. If not then refine the suggested subjects to below 17
                  $subjects = $this->Subject->find('all', array('conditions' => array("Subject.tag_ids regexp ('$list')", 'Subject.status' => '1', 'Subject.17+' => '0'), 'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image')));
                  } else {
                  $subjects = $this->Subject->find('all', array('conditions' => array("Subject.tag_ids regexp ('$list')", 'Subject.status' => '1'), 'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image')));
                  }
                 */
                $randomSubjectIds = $this->Subject->find('list', array('conditions' => array('Subject.image !=' => '', 'Subject.17+' => '0', 'Subject.status' => '1'), 'fields' => 'id', 'order' => 'RAND()', 'limit' => 50));
                $subjects = $this->Subject->find('all', array('contain' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
                    'conditions' => array('Subject.id' => $randomSubjectIds, 'Subject.image <>' => ''/* , "Subject.tag_ids regexp ('$list')" */),
                    'order' => 'RAND()'));
                //debug($subjects);
                $this->set('subjects', $subjects);

                $this->Subject->User->unbindModel(array('hasMany' => array('UserCredit', 'Subject', 'SubjectRate', 'Comment')));
                $comments = $this->Subject->Comment->find('all', array('conditions' => array('Comment.subject_id' => $subject['Subject']['id']), 'fields' => array('Comment.id', 'Comment.comment', 'Comment.created', 'Comment.user_id', 'User.id', 'User.username'), 'recursive' => '2'));
                $comments = $this->voted($comments);
                $this->set('comments', $comments);
                if ($this->Auth->User('id')) {

                    $demographics = $this->get_demographics($subject);
                    $this->set('demographics', $demographics);
                    if (!empty($demographics['populate_fields'])) {
                        $field_ids = implode(',', array_values($demographics['populate_fields']));
                        $profilefield = $this->ProfileField->query("SELECT * from profile_fields as ProfileField  where `id` IN ($field_ids) and status='1' ORDER BY `order`");
                        $this->set('profilefield', $profilefield);
                    }
                }


                //debug($this->Auth);
            } else {
                $this->Session->setFlash('Subject Not available');
                $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
            }
            $title = 'Rate The Universe - ' . ucfirst($subject['Subject']['subject']);
            $this->set('title_for_layout', $title);
            $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $this->set('url', $url);
            
            if($show_thanks=='1')
                $this->set('show_thanks', 1);
            else
                $this->set('show_thanks', 0);
        }
    }

    /*     * ************************Functions USed in Subject Function   ************************* */

    function top_adjectives($data) {
        //debug($data['SubjectAdjectives']);
        $adjectives = '';
        $adjective_ids = set::classicExtract($data['SubjectAdjectives'], '{n}.adjective_id');
        $count = array_count_values($adjective_ids);
        $total_adjectives = count($data['SubjectAdjectives']);

        $i = '0';
        foreach ($count as $key => $value):
            $i++;
            $data = $this->Adjective->find('first', array('conditions' => array('Adjective.id' => $key), 'fields' => array('Adjective.title', 'Adjective.id')));
            $percentage = round(($value / $total_adjectives) * 100, 1);
            $adjectives[$i]['id'] = $data['Adjective']['id'];
            $adjectives[$i]['title'] = $data['Adjective']['title'];
            $adjectives[$i]['percentage'] = $percentage;

        endforeach;
        $result = Set::sort($adjectives, '{n}.percentage', 'desc');
        return $result;
    }

    function get_taglist($tag_ids = null) {
        $ids = explode(',', $tag_ids);
        $tags = array();
        foreach ($ids as $key => $id) {
            $taglist[$id] = $this->find_parenttags($id, $tags);
        }

        return $taglist;
    }

    function find_parenttags($id, $tags) {
        $data = $this->Tag->find('first', array('conditions' => array('Tag.id' => $id, 'Tag.type' => 'tag'), 'fields' => array('Tag.id', 'Tag.level', 'Tag.parent_id', 'Tag.title')));
        $tags[] = $data['Tag'];
        //debug($tags);
        if ($data['Tag']['level'] > 2) {
            return $this->find_parenttags($data['Tag']['parent_id'], $tags);
        }
        return $tags;
    }

    function voted($comments) {
        $i = 0;
        foreach ($comments as $comment) {

            if (!empty($comment['CommentVote'])) {
                //echo $_SESSION['Auth']['User']['id'];
                $user_ids = set::extract($comment['CommentVote'], '{n}.user_id');
                if (in_array($this->Auth->User('id'), $user_ids))
                    $comments[$i]['voted'] = 1;else
                    $comments[$i]['voted'] = 0;
                $comments[$i]['agree'] = array_sum(set::extract($comment['CommentVote'], '{n}.agree'));
                $comments[$i]['disagree'] = array_sum(set::extract($comment['CommentVote'], '{n}.disagree'));
            }else
                $comments[$i]['voted'] = 0;
            $i++;
        }

        return $comments;
    }

    /*     * ******************  subject functions ENDS   *************************** */

    /*     * *********************************  Tag Chain Page     **************************************** */

    function tags($id = null) {
        if ($id) {
            //$this->Tag->id = '203';                        
            $childs = $this->Tag->children($id, false, 'id', 'level ASC');
            $tag_ids = array();
            foreach ($childs as $values) {
                $tag_ids[] = ','.$values['Tag']['id'].',';
            }
            $tag_ids = implode('|', $tag_ids);
            if ($tag_ids == '') {
                $tag_ids = $id;
            }

            $this->Subject->unbindModel(array('hasMany' => array('SubjectRate', 'Comment', 'Attribute', 'SubjectAdjectives', 'Subjectredirect')));
            if (isset($_SESSION['above_17']) && (!$_SESSION['above_17'])) {    // Check if user can see 17+ subject. If not then refine the suggested subjects to below 17
                //$randomSubjectIds = $this->Subject->find('list', array('conditions'=>array('Subject.image !='=>'','Subject.17+'=>'0','Subject.status'=>'1'),'fields' => 'id','order' => 'RAND()','limit' => 50));    
                $tagsubjects = $this->Subject->find('all', array('conditions' => array("Subject.tag_ids regexp ('$tag_ids')", 'Subject.status' => '1', 'Subject.17+' => '0', 'Subject.image !=' => ''), 'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'), 'order' => 'RAND()', 'limit' => 100));
            } else {
                $tagsubjects = $this->Subject->find('all', array('conditions' => array("Subject.tag_ids regexp ('$tag_ids')", 'Subject.status' => '1', 'Subject.image !=' => ''), 'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'), 'order' => 'RAND()', 'limit' => 100));
            }
            $this->set('tagsubjects', $tagsubjects);

            $tag_chain = $this->Tag->getpath($id, array('id', 'title', 'level'));

            $this->set('tag_chain', $tag_chain);

            $randomSubjectIds = $this->Subject->find('list', array('conditions' => array('Subject.image !=' => '', 'Subject.17+' => '0', 'Subject.status' => '1'), 'fields' => 'id', 'order' => 'RAND()', 'limit' => 50));
            $subjects = $this->Subject->find('all', array('contain' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
                'conditions' => array('Subject.id' => $randomSubjectIds, 'Subject.image <>' => ''),
                'order' => 'RAND()'));

            $this->set('subjects', $subjects);
        }
    }

    /*     * ************************************************************************* */

    function comment() {
        if (isset($this->data)) {
            //debug($this->data);die();
            $this->Subject->Comment->set($this->data);
            $insert_comment = mysql_query("INSERT INTO `comments` (`subject_id`,`user_id`,`comment`,`created`,`modified`) VALUES ('" . $this->data['Comment']['subject_id'] . "','" . $this->data['Comment']['user_id'] . "','" . $this->data['Comment']['comment'] . "',NOW(),NOW())");
            if ($insert_comment) {
                //$this->Session->setFlash('');
                $this->redirect(array('controller' => 'Subjects', 'action' => 'subject', $this->data['Comment']['subject_id']));
            }
        }
    }

    function comment_vote() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            if (isset($_POST['type']) && isset($_POST['id'])) {
                if ($_POST['type'] == 'agree') {
                    $insert_vote = mysql_query("INSERT INTO `comment_votes` (`comment_id`,`user_id`,`agree`,`created`) VALUES('" . $_POST['id'] . "','" . $_SESSION['Auth']['User']['id'] . "','1',NOW())") or die(mysql_error());
                } else if ($_POST['type'] == 'disagree') {
                    $insert_vote = mysql_query("INSERT INTO `comment_votes` (`comment_id`,`user_id`,`disagree`,`created`) VALUES('" . $_POST['id'] . "','" . $_SESSION['Auth']['User']['id'] . "','1',NOW()) ") or die(mysql_error());
                }
                if ($insert_vote) {
                    $count_votes = mysql_query("SELECT SUM(`agree`) as agree,SUM(`disagree`) as disagree from comment_votes where comment_id='" . $_POST['id'] . "'") or die(mysql_error());
                    $count = mysql_fetch_assoc($count_votes);
                    $response['error'] = false;
                    if ($_POST['type'] == 'agree')
                        $response['data'] = "+" . $count['agree'];
                    else
                        $response['data'] = "-" . $count['disagree'];
                } else {
                    $response['error'] = true;
                }
                $response = json_encode($response);
                echo $response;
                exit;
            }
        }
    }

    function report_comment() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            if (isset($_POST['id']) && !empty($_POST['comment'])) {
                $insert = mysql_query("INSERT INTO reported_comments (`comment_id`,`user_id`,`comment`,`created`) VALUES ('" . $_POST['id'] . "','" . $_SESSION['Auth']['User']['id'] . "','" . $_POST['comment'] . "',NOW())");
                if ($insert) {
                    echo "<div class='register-form' style='line-height:50px;font-size:15px;text-align:center; font-weight:bold;'>Thanks For Reporting this Comment</div>";
                }
            }
        }
    }

    function adjectives() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $adjectives = $this->Adjective->find('all', array('conditions' => array('Adjective.title LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
            $i = 0;
            if ($adjectives) {
                foreach ($adjectives as $adjective) {
                    $response[$i]['id'] = $adjective['Adjective']['id'];
                    $response[$i]['name'] = "" . $adjective['Adjective']['title'] . "";
                    $i++;
                }
                if (isset($_GET["callback"])) {
                    $response = $_GET["callback"] . "(" . $response . ")";
                }
            } else {
                $response[$i]['id'] = $_GET['q'];
                $response[$i]['name'] = "" . $_GET['q'] . "<div style='cursor:pointer;line-height:30px'> No Such Adjective. <span style='border:1px solid #fff;padding:5px;cursor:pointer;'>Suggest Now</span></div>";
            }
            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************************** Adjective function ends  *********************************** */

    function admin_synonyms() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 2);
            $this->autoRender = false;
            $response = array();
            $subjectlist = array();
            //echo $_POST['search'];
            //$data = mysql_query("SELECT `subject`,`desc` from `subject` where `subject` LIKE '%" . $_GET['search'] . "%' || `desc` LIKE '%" . $_GET['search'] . "%'") or die(mysql_error());
            $data = mysql_query("SELECT `subject`,`desc` from `subject` WHERE `subject`!='" . $_GET['search'] . "'") or die(mysql_error());
            while ($row = mysql_fetch_array($data)) {
                if (!empty($row['desc'])) {
                    $subjectlist[] = $row['subject'] . " (" . $row['desc'] . ")";
                    //$subjectlist[] = $row['subject'] . " " . $row['desc'];
                } else {
                    $subjectlist[] = $row['subject'];
                }
            }


            //$data=$this->Subject->find('all',array('conditions'=>array('Subject.subject LIKE'=>'%'.$_GET['search'].'%')));
            // print_r($subjectlist);
//$_GET['offset']=0;
            //echo "<pre>";
            //print_r($subjectlist);

            $i = 0;
            $offset = 0;
            $search = stripslashes($_GET['search']);
            $response = array(array('id' => $search, 'name' => $search));
            $searchfor = str_replace(' ', '_', ucfirst($search));
            $result = $this->get_wiki_titles($response, $searchfor, $offset, $i, $subjectlist);
            //$result = $this->get_wiki_titles($response,$_GET['search'], $offset, $i,$subjectlist);
//            foreach ($result->query->search as $subject) {
//                if (!in_array($subject->title, $subjectlist)) {
//                    $response[$i]['id'] = $subject->title;
//                    $response[$i]['name'] = $subject->title;
//                    $i++;
//                } else if ($i == '51') {
//                    break;
//                } else {
//                    continue;
//                }
//            }

            $response = json_encode($result);
            echo $response;


//
//echo "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&limit=20&search=".$_POST['search'];
//            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
//            $i = 0;
//            foreach ($subjects as $subject) {
//                $response[$i]['id'] = $subject['Subject']['id'];
//                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "";
//                $i++;
//            }
//            if (isset($_GET["callback"])) {
//                $response = $_GET["callback"] . "(" . $response . ")";
//            }
//
//            $response = json_encode($response);
//            echo $response;
        }
    }

//    function admin_synonymsbackup() {
//        if ($this->RequestHandler->isAjax()) {
//            Configure::write('debug', 0);
//            $this->autoRender = false;
//            $response = array();
//            $subjectlist=array();
//            //echo $_POST['search'];
//       
////
////echo "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&limit=20&search=".$_POST['search'];
//
//            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => '%' . $_GET['q'] . '%'), 'limit' => '10'));
//            $i = 0;
//            foreach ($subjects as $subject) {
//                $response[$i]['id'] = $subject['Subject']['id'];
//                $response[$i]['name'] = "" . $subject['Subject']['subject'] . "";
//                $i++;
//            }
//            if (isset($_GET["callback"])) {
//                $response = $_GET["callback"] . "(" . $response . ")";
//            }
//
//            $response = json_encode($response);
//            echo $response;
//        }
//    }
//    
//
    /*     * ************************** Tag function is called from edit and add. Called in Option tree  widget. ********************************************* */

    function admin_tags() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            if (!isset($_GET['id'])) {
                $_GET['id'] = '2';
            }
            $this->autoRender = false;
            if (isset($_GET['id']) && $_GET['id'] != '0') {
                $tags = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $_GET['id'], 'Tag.type !=' => 'attribute'), 'order' => 'Tag.position asc'));
            }
            if (!empty($tags)) {
                $response['0'] = "select Tag";
            }
            $i = 0;

            foreach ($tags as $tag) {
                $response[$tag['Tag']['id']] = "" . $tag['Tag']['title'] . "";
                $i++;
            }
            $response = json_encode($response);
            echo $response;
        }
    }

    /*     * ************ Tag function ends************ */

    function get_parent_list($id, $result_arr = array()) {
        $tag = $this->Tag->find('first', array('conditions' => array('Tag.id =' => $id)));
        $result_arr[] = array('id' => $tag['Tag']['parent_id'], 'title' => $tag['Tag']['title']);

        if ($tag['Tag']['level'] > '2') {
            return $this->get_parent_list($tag['Tag']['parent_id'], $result_arr);
        }
        return $result_arr;
    }

    function formated_tags($title_arr, $saparater = '>') {
        $titles = '';
        $title_arr = array_reverse($title_arr);
        foreach ($title_arr as $title) {

            $titles.=$saparater . $title['title'];
        }
        return substr($titles, strlen($saparater));
    }

    /*     * ******************* Function  to delete image while editing subject************************* */

    function admin_delete_image($id = null) {
        if (!empty($id)) {

            $query = mysql_query("UPDATE `subject` set `image`='' WHERE id='" . $id . "'");
            $data = $this->Subject->find('first', array('conditiond' => array('Subject.id =' => $id)));
            $dir = WWW_ROOT . 'img/uploads/Subjects/' . $data['Subject']['subject'] . '/' . $data['Subject']['image'];
            $file = new File($dir);
            if ($query) {
                if ($file) {
                    $file->delete();
                    $this->redirect(array('controller' => 'Subjects', 'action' => 'edit', $id));
                }
            }
        }
    }

    function synonymlist($id) {
        if ($id) {
            $data = $this->Subject->find('all', array('conditions' => array('Subject.subject_id' => $id), 'fields' => array('Subject.subject', 'Subject.id')));
            //debug($data);
            $synonym_data = array();

            $i = 0;
            foreach ($data as $subject) {
                $synonym_data[$i]['id'] = $subject['Subject']['id'];
                $synonym_data[$i]['name'] = $subject['Subject']['subject'];
                $i++;
            }
            return $synonym_data;
        }
    }

    function admin_attributes($id = null) {
        $this->layout = 'Ajax';
        /*         * ******** Initialize all variables here********* */


        /*         * *************Initialization Ends*************** */

        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            //$this->autoRender = false;
            //$this->layout='Ajax';

            $id = $_REQUEST['id'];
            $old_attrib_num = $_POST['num'];      //Number of Attribute fields already in the form.
            if ($old_attrib_num == '0') {
                $n = 0;
            } else {
                $n = ceil($old_attrib_num / 3) + 1;
            }
            $metadata = array('n' => $n, 'id' => $id);
            $data = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $id, 'Tag.type =' => 'attribute')));
            $this->set('attributes', $data);
            $this->set('meta', $metadata);


            //$this->render('/elements/admin_attributes');
        }
    }

    function formated_attributes($attributes, $i) {

        $result = "<div class='inputattributes'><div style='float:left; padding-right:10px;'>" . $attributes['Tag']['title'] . "</div>
                <div >
                <input id='Attribute" . $i . "attribute' type='hidden' name='data[Attribute][$i][attribute]' value='" . $attributes['Tag']['title'] . "'/>
                " . $this->Form->input('Attribute' . $i . 'value') . "</div></div><br><div style='clear:both;height:10px;'></div>";
        return $result;
    }

    /*     * ********************  This Function will ruturn the search result for subjects    ********************* */

    function admin_search() {

        $data = $this->paginate('Subject', array('OR' => array(array('Subject.desc =' => $this->data['Subject']['search']), array('Subject.subject =' => $this->data['Subject']['search']))));
        $adjectives = '';
        $taglist = '';
        $i = 0;

        /*         * ********  Loop through the fetched data to get Formated Taglist and Adjectives      ****** */

        foreach ($data as $value) {
            $adj_ids = explode(',', $value['Subject']['adjective_ids']);
            $tag_ids = explode(',', $value['Subject']['tag_ids']);

            /*             * ************************* This loop will get you the Adjectives from adjective_ids     ************************ */
            foreach ($adj_ids as $id) {
                $adj = $this->Adjective->find('first', array('conditions' => array('Adjective.id =' => $id)));
                $adjectives = $adjectives . ',' . $adj['Adjective']['title'];
            }


            /*             * ************** 
             * This loop will get all the formated tags for a particular record.
             *  Functions used : 
             *                  get_parent_list($tid):accepts tag_id as input. this will return an array with parent ids and parent titles.
             *                  formated_tags($tag_arr,$saparator):First argument is the tag_array returned from get_parent_list.Second parameter is optional. This will be used as to format taglist.
             * 
             * *************** */
            foreach ($tag_ids as $tid) {
                $tag_arr = $this->get_parent_list($tid);
                $taglist = $this->formated_tags($tag_arr, '>');
            }
            $data[$i]['Subject']['adjective_ids'] = substr($adjectives, 1);
            $data[$i]['Subject']['tag_ids'] = $taglist;
            $i++;
            $adjectives = '';
            //$tags='';
        }

        /*         * **********  Loop to get Taglist and Adjectives ENDS     ******************** */

        //debug($data);
        $this->set('Subjects', $data);
    }

    /*     * ******************** This function  is used in autocomplete for search in subject   ******************* */

    function admin_search_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => $_GET['q'] . '%'), 'fields' => array('Subject.subject', 'Subject.id', 'Subject.desc')));
            if (empty($subjects)) {
                $subjects = $this->Subject->find('all', array('conditions' => array('Subject.desc LIKE' => $_GET['q'] . '%')));
            }
            $i = 0;

            foreach ($subjects as $subject) {
                $specifier = '';
                $response[$i]['id'] = $subject['Subject']['subject'];
                if ($subject['Subject']['desc']) {
                    $specifier = '(' . $subject['Subject']['desc'] . ')';
                }
                $response[$i]['name'] = "" . $subject['Subject']['subject'] . $specifier;
                $i++;
            }
            if (isset($_GET["callback"])) {
                $response = $_GET["callback"] . "(" . $response . ")";
            }

            $response = json_encode($response);
            echo $response;
        }
    }

    function admin_subject_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $title = $_GET['title'];
            $specifier = $_GET['specifier'];
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject' => $title, 'Subject.desc' => $specifier)));

            if ($subjects) {
                return true;
            } else {
                return false;
            }
        }
    }

    function check_image_extension($ext) {
        $response = false;
        $allowedext = array('jpg', 'JPG', 'jpeg', 'JPEG', 'pjpeg', 'png', 'PNG');
        foreach ($allowedext as $extension) {
            if ($extension == $ext) {
                $response = true;
                break;
            }
        }
        return $response;
    }

    function admin_tag() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            $ids = array_reverse($this->get_parent_list($_POST['id']));
            // print_r($ids);
            foreach ($ids as $value) {
                $id = $id . $value['id'] . ',';
            }
            echo $id . $_POST['id'] . ',0';


            //echo '206,243,205,0';
            $response = json_encode($response);
            //echo $response;
        }
    }

    function admin_update() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            if (!empty($_POST['id'])) {
                //$query=mysql_query('UPDATE ');

                $this->Subject->id = $_POST['id'];
                $this->data['Subject']['status'] = $_POST['status'];
                $this->Subject->save($this->data);
            }
        }
    }

    function admin_report() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            if (!empty($_POST['id'])) {
                //$query=mysql_query('UPDATE ');
                $query = mysql_query("INSERT INTO `flagged_subjects` (`subject_id`,`user_id`,`type`,`comment`,`created`,`modified`)
                                                VALUES('" . $_POST['subject_id'] . "','" . $_POST['id'] . "','" . $_POST['type'] . "','" . $_POST['comment'] . "',now(),now())
                                   ");
                echo "<div class='thanks'>Thanks for reporting</div>";
            }
        }
    }

    function saveCredit($data) {
        $p = 0;

        $balance = $this->balance($data['User']['id']);

        foreach ($data['Subject'] as $key => $value) {
            if ($value == '1') {
                $point = $this->Credit->find('first', array('conditions' => array('Credit.id' => $key)));

                $this->data['UserCredit'][$p]['credit'] = $point['Credit']['point'];
                $this->data['UserCredit'][$p]['credit_id'] = $key;
                $this->data['UserCredit'][$p]['user_id'] = $data['User']['id'];
                $this->data['UserCredit'][$p]['subject_id'] = $data['Subject']['id'];

                $this->data['UserCredit'][$p]['balance'] = $balance + $this->data['UserCredit'][$p]['credit'];
                //$this->UserCredit->save($this->data['UserCredit']);
                $balance = $this->data['UserCredit'][$p]['balance'];
                $p++;
            }
        }
        if (!empty($this->data['UserCredit'])) {
            $this->UserCredit->saveAll($this->data['UserCredit']);
        }
    }

    function balance($id) {
        $points = $this->Subject->query("SELECT SUM(user_credits.credit) as balance FROM `user_credits` where user_id='$id'");
        return @$points[0][0]['balance'];
    }

    /*     * ***************  This function will set the current edited subject as a base subject for the selected  Subject synonyms. It takes $this->data as parameter********************** */

    function set_base_subject($data) {
        $subject_ids = explode(',', $this->data['Subject']['subject_ids']);
        $old_subject_ids = explode(',', $this->data['Subject']['old_subject_ids']);

        $deletedsyn = array_diff($old_subject_ids, $subject_ids);
        // debug($subject_ids);
        //debug($data);die();
        foreach ($deletedsyn as $id) {
            $update_subject_id = $this->Subject->query("UPDATE `subject` set `subject_id`='0' WHERE `id`='" . $id . "'");
        }
        foreach ($subject_ids as $subject_id)
            $update_subject_id = $this->Subject->query("UPDATE `subject` set `subject_id`='" . $this->data['Subject']['id'] . "' WHERE `id`='" . $subject_id . "'");
        return true;
    }

    function get_suggestion() {

        $subjects = $this->Page->find('all', array('limit' => '100', 'conditions' => array('Page.page_title LIKE' => $search . '%', 'Page.page_is_redirect' => '0'), 'fields' => array('Page.page_id', 'Page.page_title'), 'recursive' => '-1'));

//        foreach($subjects as $key1=>$redirects):
//            foreach($redirects['Pageredirect'] as $key=>$value):
//                $find_redirect=$this->Page->find('first',array('conditions'=>array('Page.page_id'=>$value['rd_from'])));
//                if($find_redirect){
//                    
//                
//                $subjects[$key1]['Page']['redirect_title'][$key]['id']=$find_redirect['Page']['page_id'];    
//                $subjects[$key1]['Page']['redirect_title'][$key]['title']=$find_redirect['Page']['page_title'];
//                }
//            endforeach;
//        endforeach;
//        //debug($results);  

        $this->set('subjects', $subjects);
    }

    function get_wiki_titles($response, $search, $offset, $i, $subjectlist) {
//      $res=json_encode($response);
//        print_r($subjectlist);
//        $useragent = env('HTTP_USER_AGENT');
//        $url = "http://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=intitle%3A".urlencode($_GET['search'])."%&srprop=hasrelated&srlimit=50&sroffset=" . $offset . "&format=json&what=title";
//        //echo $url;die();
//        $ch = curl_init($url);
//
//   set user agent
//       curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
///////  $ch = curl_init ($url) ;
//       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//       $res = json_decode(curl_exec($ch));
//       print_r($res);
//       curl_close($ch);
//       die();//print_r($res);
        //$search=htmlspecialchars_decode ($search);
        $subjects = $this->Page->find('all', array('limit' => '100', 'conditions' => array('Page.page_title LIKE' => $search . '%', 'Page.page_is_redirect' => '0', 'Page.page_namespace' => '0'), 'fields' => array('DISTINCT Page.page_title', 'Page.page_id'), 'recursive' => '-1'));
        if ($subjects) {
            foreach ($subjects as $subject) {
                if (!in_array($subject['Page']['page_title'], $subjectlist) && !in_array($subject['Page']['page_title'], $response)) {
                    if (!strpos($subject['Page']['page_title'], '(disambiguation)')) {
                        $response[$i]['id'] = $subject['Page']['page_title'];
                        $response[$i]['name'] = str_replace('_', ' ', $subject['Page']['page_title']);
                        $i++;
                    }
                }
                if ($i == '50') {
                    break;
                }
            }

            if ($i < '50' && count($subjects) > '50') {
                return $this->get_wiki_titles($response, $search, 50 + $offset, $i, $subjectlist);
            } else {
                if (count($response) > '0') {
                    return $response;
                }
            }
        }
        if (!$response) {

            //$findsubject=$this->Subject->find('all',array('limit'=>'1000','conditions'=>array('Subject.subject LIKE'=>$search)));
            //print_r($findsubject);
            //echo count($findsubject);

            $name = str_replace('_', ' ', $search);
            $response = array(array('id' => $name, 'name' => $name));
            return $response;
        }
        return $response;
    }

    function get_related_subjects($subject) {

        $data = $this->Subject->find('all', array('conditions' => array('Subject.subject LIKE' => $subject . ' %'), 'fields' => array('Subject.subject', 'Subject.desc')));
        foreach ($data as $key => $value) {
            $data[$key]['Subject']['rating_count'] = count($value['SubjectRate']);
        }
        return $data;
    }

    function get_redirects() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $result = '';
            $subjecttitle = $_POST['subject'];

            $data = $this->Pageredirect->find('all', array('conditions' => array('Pageredirect.rd_title' => $subjecttitle)));
            if ($data) {
                foreach ($data as $key => $titles):
                    foreach ($titles['Page'] as $redirects):

                        $result.=', ' . str_replace('_', ' ', $redirects['page_title']);
                    endforeach;
                endforeach;
            }
            $response = trim($result, ', ');
            //$response='adasdas';
            return $response;
            //debug($data);
            //$this->set('subjects', $result);
        }
    }

    function login_element() {
        //echo phpinfo();

        $this->layout = "";
        //echo $this->element('login');
    }

    /*     * *****************This function checks when was subject last rated by a user ********************************* */

    function rate_time($subject_id, $user_id) {
        $data = $this->Subject->SubjectRate->find('count', array(
            'conditions' => array(
                'SubjectRate.subject_id' => $subject_id,
                'SubjectRate.user_id' => $user_id,
                'SubjectRate.created >=DATE_SUB(CURDATE(),INTERVAL 7 DAY)'
            ),
            'order' => 'SubjectRate.created desc',
            'limit' => '1'
                )
        );

        return $data;
    }

    /*     * *********** This function will generate resized image for the rated subject **************** */

    function generatepopupimage() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->layout = "";
            $result = '';
            $data = $this->Subject->find('first', array('conditions' => array('Subject.id' => $_POST['subject'])));
            if ($data) {
                $this->set('subject', $data);
            }
        }
    }

    function admin_correction() {
//        $data=$this->Subject->find('all',array('recursive'=>'-1'));
//        debug($data);
//        foreach($data as $subject):
//            if(!e
//            mpty($subject['Subject']['adjective_ids'])){
//                $adjective_ids=explode(',',$subject['Subject']['adjective_ids']);
//                foreach($adjective_ids as $adjective){
//                    $query=mysql_query("INSERT INTO  `subject_adjectives` (`adjective_id`,`user_id`,`subject_id`,`created`,`status`)
//                             VALUES ('".$adjective."','".$subject['Subject']['user_id']."','".$subject['Subject']['id']."','".$subject['Subject']['approved_on']."','0')");
//                }
//            }
//        endforeach;
//        
    }

    function multidimensional_search($parents, $searched) {
        if (empty($searched) || empty($parents)) {
            return false;
        }

        foreach ($parents as $key => $value) {
            $exists = true;
            foreach ($searched as $skey => $svalue) {
                $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
            }
            if ($exists) {
                return $key;
            }
        }

        return false;
    }

    function add() {

        if (isset($this->data)) {

            $tags = array();

            if (isset($_POST['tag_ids'])) {
                $tags = $_POST['tag_ids'];
            }
            $uniquetags = array_unique($tags);

            $tag_ids = implode(',', $uniquetags);
            $tag_ids = ltrim($tag_ids, ',');
            $this->data['Subject']['tag_ids'] = $tag_ids;

            if ($this->data['Subject']['image']['error'] == '0') {
                $ext = pathinfo(WWW_ROOT . 'img/uploads/Subjects/' . $this->data['Subject']['image']['name']);
                if ($this->check_image_extension($ext['extension'])) {
                    $image_name = uniqid($this->data['Subject']['subject'], true) . '.' . $ext['extension'];
                    if (!file_exists(WWW_ROOT . 'img/uploads/Subjects/' . $image_name)) {
                        move_uploaded_file($this->data['Subject']['image']['tmp_name'], WWW_ROOT . 'img/uploads/Subjects/' . $image_name);
                    }
                    $this->data['Subject']['image'] = $image_name;
                } else {
                    $this->data['Subject']['image'] = '';
                }
            } else {
                $this->data['Subject']['image'] = '';
            }
            $this->data['Subject']['user_id'] = $_SESSION['Auth']['User']['id'];
            $this->data['Subject']['desc'] = strtolower($this->data['Subject']['desc']);

            //$this->data=$this->set_adjective_array($this->data);
            if ($this->Subject->saveAll($this->data, array('validate' => 'first'))) {
                /* print_r($_POST);
                  debug($this->data);die(); */
                if (!empty($this->data['Subject']['adjective_ids'])) {

                    $this->admin_save_adjectives($this->data['Subject']['adjective_ids'], $this->Subject->id);
                }
                $this->data['SubjectRate']['subject_id'] = $this->Subject->id;
                $this->data['SubjectRate']['user_id'] = $_SESSION['Auth']['User']['id'];
                $this->data['SubjectRate']['rating'] = $_POST['rating'];
                $this->Subject->SubjectRate->save($this->data, array('validate' => 'only'));
                $this->Session->setFlash('You have successfuly added a subject. Wait for admin approval');
                $this->redirect(array('controller' => 'Homes', 'action' => 'index', 'status' => '0'));
            }
        }
    }

    function get_demographics($data) {
        //$this->Point->check_account();
        //$field_ids=$this->get_user_data($user_id); //will return field ids that have been shared

        $response['stats'] = false;
        $user_ids = array_unique(set::classicExtract($data['SubjectRate'], '{n}.user_id'));
        $profile_data = $this->find_profile_values($user_ids, $data['Subject']['id']); // will return an array of each users profile field values
        $response['stats'] = $profile_data['data'];
        /*
          if ($profile_data['data']) {
          $response['stats'] = $this->calculate_stats($data, $profile_data['data'], $user_ids);
          //debug($stats);die();

          } else {

          $response['stats']= false;
          }
         */
        $response['populate_fields'] = $profile_data['populate_fields'];
        return $response;
        //$ratings=$this->SubjectRate->find('all',array('conditions'=>array('SubjectRate.subject_id'=>$id),'fields'=>array('SubjectRate.user_id','SubjectRate.rating')));
        //   $users_ids=implode(',',set::classicExtract($ratings,'{n}.SubjectRate.user_id'));//debug($users_ids); 
        //    $this->User->unbindModel(array('hasMany' => array('UserCredit','Subject','SubjectRate')));
        //$userinfo=$this->ProfileFieldValue->find('all',array('conditions'=>array('ProfileFieldValue.user_id'=>$this->Auth->User('id'),'ProfieField.type'=>"select",'ProfieField.status'=>'1')));
        //$userinfo=$this->ProfileFieldValue->find('all',array('conditions'=>array("ProfileFieldValue.user_id IN($users_ids)",'ProfieField.type'=>"select")));
        //debug($userinfo);
    }

    function find_profile_values($ids, $subject_id) {
        $response['populate_fields'] = '';
        $response['data'] = false;
        $user_id = $this->Auth->User('id');

        // debug($ids);
        //debug($_SESSION);die();
        $idlist = implode(',', $ids);
        $this->User->unbindModel(array('hasMany' => array('Subject', 'UserCredit', 'SubjectRate')));
        //    $get_select_type_fields = $this->ProfileField->find('list', array('conditions' => array('ProfileField.type' => 'select', 'ProfileField.status' => '1')));
        $get_select_type_fields = $this->ProfileField->query("
            SELECT pf.id, pf.title, pf.type, pf.value, pv.user_id, pv.value
              FROM profile_fields pf LEFT JOIN (SELECT * FROM profile_field_values WHERE user_id = $user_id) AS pv ON pf.id = pv.profile_field_id 
             WHERE pf.status = 1 AND pf.type = 'select'
             ORDER BY pf.order");
        //debug($get_select_type_fields);

        foreach ($get_select_type_fields as &$type_field) {
            if (isset($type_field['pv']['user_id'])) {
                $profile_id = $type_field['pf']['id'];
                $total = $this->ProfileFieldValue->find('count', array('conditions' => array('user_id' => $ids, 'profile_field_id' => $profile_id)));
                if ($total > 0) {
                    $rough_values = $this->ProfileFieldValue->query("
                        SELECT value, ROUND(COUNT(*)/$total, 1) * 100 as value_percent, 
                               GROUP_CONCAT(DISTINCT user_id separator ',') as user_ids
                          FROM profile_field_values 
                         WHERE user_id IN ($idlist)
                          AND profile_field_id = $profile_id
                         GROUP BY value 
                         ORDER BY value");
                    $statistic_data = array();
                    foreach ($rough_values as $key => $rough_value) {
                        $statistic_data[$key]['profile_field_value'] = $this->_convert_profile_val($profile_id,$rough_value['profile_field_values']['value']);//$rough_value['profile_field_values']['value'];
                        $statistic_data[$key]['value_percent'] = $rough_value['0']['value_percent'];
                        $avg_rating = $this->SubjectRate->find('first', array('conditions' => array("SubjectRate.user_id IN (" . $rough_value['0']['user_ids'] . ")", 'SubjectRate.subject_id' => $subject_id), 'fields' => array('AVG(SubjectRate.rating) as rating')));
                        $statistic_data[$key]['avg_rating'] = $avg_rating[0]['rating'];
                    }
                    $type_field['statistic_data'] = $statistic_data;
                }
            }
        }
        $response['data'] = $get_select_type_fields;
        /*
          $account_type = $this->User->query("SELECT `account_type`,`free_account_type` from user_profiles where user_id='" . $this->Auth->User('id') . "'");
          // debug($account_type);die();
          if (count($account_type) == '1') {
          if (!empty($account_type['0']['user_profiles']['account_type'])) {
          $account_type = $account_type['0']['user_profiles']['account_type'];
          } else {
          $account_type = $account_type['0']['user_profiles']['free_account_type'];
          }
          }


          if ($account_type == 'free') {
          $user_shared_fields = $this->ProfileFieldValue->find('list', array('conditions' => array('ProfileFieldValue.user_id' => $this->Auth->User('id'), 'ProfileFieldValue.value !=' => ''), 'fields' => array('ProfileFieldValue.profile_field_id')));
          $candidate_fields = array_flip(array_intersect(array_flip($get_select_type_fields), $user_shared_fields));
          //debug($user_shared_fields);
          //debug($candidate_fields);//die();
          }

          if(isset($user_shared_fields))
          $populate_fields = array_diff(array_flip($get_select_type_fields), $user_shared_fields);
          else
          $populate_fields = array();
          $response['populate_fields'] = $populate_fields;
          //debug($populate_fields);

          if (empty($candidate_fields)) {                 // If User has'nt filled any info he will be asked to fill in the info. Call the function for that
          $response['data']=false;
          } else {


          $profile_field_ids = implode(',', array_keys($candidate_fields));
          //echo "SELECT `value`,GROUP_CONCAT(DISTINCT `user_id` separator ',') FROM `profile_field_values`  GROUP BY `value`";
          //$set_max_group_concat_length = $this->ProfileFieldValue->query("SET SESSION group_concat_max_len=512");
          $d1 = $this->ProfileFieldValue->query("SELECT *, count(`value`) as value_count,GROUP_CONCAT(DISTINCT `user_id` separator ',') as user_ids  FROM `profile_field_values` WHERE user_id  IN ($idlist) and profile_field_id IN(" . $profile_field_ids . ") AND `value` !='' GROUP BY `value` ORDER BY `profile_field_id`");
          //die();
          //$user_data=$this->User->find('all',array('conditions'=>array("User.id IN ($idlist) "),'recursive'=>'2','join'=>array()));
          if (count($d1) > 0) {

          foreach ($d1 as $key => $value) {
          $avg_rating = $this->SubjectRate->find('first', array('conditions' => array("SubjectRate.user_id IN (" . $value['0']['user_ids'] . ")", 'SubjectRate.subject_id' => $subject_id), 'fields' => array('AVG(SubjectRate.rating) as rating')));
          $value['0']['rating'] = $avg_rating['0']['rating'];
          $data[$value['profile_field_values']['profile_field_id']][] = $value;
          }
          $response['data']= $data;
          } else {
          $response['data']=false;                    //Return false if no data is available for voters
          }
          }
         */
        return $response;
    }

    function calculate_stats($data, $profile_data, $user_ids) {

        //debug($data);  
        //debug($profile_data);die();
        // debug($user_ids);
        $stats = array();
        $total_voters = count($user_ids);
        foreach ($profile_data as $key => $pdata) {
            $total_percentage = '';
            $total_rating = '';
            $voters = '';
            foreach ($pdata as $value) {
                //  $res=Set::matches(array('id>=2'), $a[1]['Article']);
                $stats[$key][$value['profile_field_values']['value']]['percentage'] = round(($value['0']['value_count'] / $total_voters) * 100, 2);
                $total_percentage+=($value['0']['value_count'] / $total_voters) * 100;

                $total_rating+=$value['0']['rating'] * $value['0']['value_count'];

                $stats[$key][$value['profile_field_values']['value']]['urating'] = round($value['0']['rating'], 2);
                $stats[$key][$value['profile_field_values']['value']]['voters'] = $value['0']['value_count'];
                $voters+=$value['0']['value_count'];
            }

            if ($total_percentage != '100') {
                $stats[$key]['other']['percentage'] = round((100 - $total_percentage), 2);

                $stats[$key]['other']['voters'] = count($data['SubjectRate']) - $voters;
                $stats[$key]['other']['urating'] = round((($data['Subject']['avg_rating'] * count($data['SubjectRate']) - $total_rating) / $stats[$key]['other']['voters']), 2);
            }
        }
        //debug($stats);
        //return $stats;
        $keys = implode(',', array_keys($stats));
        $key_titles = $this->ProfileField->find('list', array('conditions' => array("ProfileField.id IN ($keys)"), 'fields' => 'ProfileField.title'));
        // debug($key_titles);
        $result = array_combine($key_titles, $stats);
        return $result;
    }

    function add_profile_fields() {

        if ($this->data['Tag']) {
            $this->data['Profiles'] = $this->data['Tag'];
        }

        foreach ($this->data['Profiles'] as $key => $profile) {

            if (strstr($key, 'status')) {
                $keys = substr($key, 6);
                if (!in_array($keys, $rowss)) {
                    if (is_array($profile)) {
                        $profile = implode($profile, ',');
                    }
                    if ($profile == '0') {
                        $profile = '';
                    }

                    $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`) value('" . $_SESSION['Auth']['user']['User']['id'] . "','" . str_replace("status", "", $key) . "','$profile')";
                    mysql_query($insert) or die(mysql_errno());
                } else if (strstr($key, 'status')) {

                    $update1 = "update profile_field_values set status='$profile' where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "' AND profile_field_id='" . str_replace("status", "", $key) . "'";
                    mysql_query($update1) or die(mysql_error());
                }
            } else {
                if (is_array($profile)) {
                    $profile = implode($profile, ',');
                }
                if ($profile == '0') {
                    $profile = '';
                }
                $update2 = "update profile_field_values set value='$profile' where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "' AND profile_field_id='" . str_replace("status", "", $key) . "'";

                mysql_query($update2) or die(mysql_errno());
            }
        }

        $this->redirect(array('controller' => 'Subjects', 'action' => '../subject', $this->data['Profiles']['subject']));
    }

    function history_graph($id) {
        $interval = $this->Subject->SubjectRate->find('first', array('conditions' => array('SubjectRate.subject_id' => $id), 'fields' => array("TIMESTAMPDIFF(HOUR , MIN( SubjectRate.created ) ,NOW()) as interval_in_hours", "MIN( SubjectRate.created) as inception")));

        if ($interval) {
            if (isset($interval['0']['interval_in_hours'])) {
                $inception = $interval['0']['inception'];
                $interval = floor($interval['0']['interval_in_hours'] / 10);
            }
            $end = '0';
            $result = array();
            for ($i = '0'; $i < 10; $i++) {

                if ($i == '9') {
                    $end+=$interval;
                }
                $end+=$interval;
                $history = $this->Subject->SubjectRate->find('all', array('conditions' => array('SubjectRate.subject_id' => $id, "SubjectRate.created BETWEEN '$inception' AND TIMESTAMPADD(HOUR , $end,'$inception')"), 'order' => array('SubjectRate.created asc'), 'fields' => array('AVG(SubjectRate.rating) AS rating', 'SubjectRate.created', "TIMESTAMPADD(HOUR , $end,'$inception') as enddate", "GROUP_CONCAT(DISTINCT `SubjectRate`.`rating` separator ',') as rating_val ")));
                $result[$i] = $history['0'];
            }
            $history = $result;
            $output = '[';
            $output_array = array();
            $i = 0;
            foreach ($history as $data):$i++;
                $output_array[$i] = "['" . $data['0']['enddate'] . "'," . round($data['0']['rating'], 2) . "]";
            endforeach;
            $output_data = implode(',', $output_array);
            $output = '[' . $output_data . ']';

            return $output;
        }
    }

    function subject_list($creator_id = null) {
        $this->set('title_for_layout', 'Rate The Universe - Subject list');
        Configure::write('debug', -1);

        if (!isset($creator_id))
            $this->redirect(array('controller' => 'homes', 'action' => 'index'));

        $this->set('rank', $this->UserCredit->get_user_ranking($creator_id));
        $points = $this->UserCredit->get_points($creator_id);
        $this->set('points', $points);
        $ratedsubjects = $this->SubjectRate->find('count', array('conditions' => array('SubjectRate.user_id' => $creator_id), 'fields' => 'DISTINCT SubjectRate.subject_id'));
        $this->set('subjects_rated', $ratedsubjects);
        $subject_added = $this->Subject->find('count', array('conditions' => array('Subject.user_id' => $creator_id, 'Subject.status' => '1')));
        $this->set('subject_added', $subject_added);
        $this->set('level', $this->UserCredit->get_level($points));

        $userdetail = $this->User->find('first', array('conditions' => array('user_id' => $creator_id)));
        $this->set('userdetail', $userdetail);


        $conditions = array('Subject.image !=' => '', 'Subject.17+' => '0', 'Subject.status' => '1', 'Subject.user_id' => $creator_id);
        $join_table = array(array('table' => 'subject_rates',
                'alias' => 'Subject_Rate',
                'type' => 'inner',
                'conditions' => array('Subject.id = Subject_Rate.subject_id')
                ));
        $this->paginate = array('limit' => 20,
            'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'AVG(Subject_Rate.rating) as avg_rating'),
            'joins' => $join_table,
            'conditions' => $conditions,
            'recursive' => 0,
            'group' => array('Subject.subject', 'Subject.desc', 'Subject.id'),
            'order' => 'Subject.subject'
        );
        $data = $this->paginate('Subject');
        $this->set(compact('data'));
    }

    function search() {
        $this->set('title_for_layout', 'Rate The Universe - Search results');
        Configure::write('debug', -1);
        if (isset($_POST['subject'])) {
            $keyword = $_POST['subject'];
            $_SESSION['search_subject'] = $keyword;
        }else
            if(isset($_SESSION['search_subject']))
                $keyword = $_SESSION['search_subject'];
            else
                $keyword = '';
        if(isset($_POST['search_type'])){
            $type = $_POST['search_type'];
        }else{
            $type = 0;//0: subject - 1: tag
        }
        
        if($type==0){
            $conditions = array('Subject.image !=' => '', 'Subject.17+' => '0', 'Subject.status' => '1');
            if (isset($keyword))
                $conditions['Subject.subject like'] = "%$keyword%";
            $this->paginate = array('fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
                'conditions' => $conditions,
                'recursive' => 0,
                'order' => 'Subject.subject',
                'limit' => 30);
            $data = $this->paginate('Subject');
            $this->set(compact('data', 'keyword'));
        }else{
            //Tag process : retrieve the subject_id array
            $this->Subject->unbindModel(array('hasMany' => array('SubjectRate', 'Comment', 'Attribute', 'SubjectAdjectives', 'Subjectredirect')));
            if(!empty($keyword))
            {
                //get the tag row whose title is the same
                $id_arr_htags = array();                
                $tmp = $this->Tag->find('all', 
                        array(
                            'conditions' => array(
                                'title LIKE'=>"%$keyword%"), 
                            'fields' => array('Tag.id'), 
                            'order' => 'Tag.id ASC'));
                foreach($tmp as $tmp_item)
                    $id_arr_htags[] = $tmp_item['Tag']['id'];
                
                $tag_ids = array();
                //get the children of the tag
                foreach($id_arr_htags as $item){
                    $tag_ids[] = $item;
                    $childs = $this->Tag->children($item, false, 'id', 'level ASC');
                    foreach ($childs as $values) {
                        $tmp_val = ",".$values['Tag']['id'].',';
//                        $tmp_val = '^'.$tmp_val.'$';
//                        $tag_ids[] = '^'.$tmp_val.'$'."|^$tmp_val,"."|,$tmp_val$"."|,$tmp_val,";
                        $tag_ids[] = $tmp_val;
                    }           
                }
                
                //convert tag_ids to string for regexp
                $str_tag_ids = implode('|', $tag_ids);
                if (empty($str_tag_ids)) {
                    $str_tag_ids = implode('|', $id_arr_htags);
                }
//                $tagsubjects = $this->Subject->find('all', 
//                        array(
//                            'conditions' => array("Subject.tag_ids regexp ('$str_tag_ids')", 'Subject.status' => '1', 'Subject.image !=' => ''), 
//                            'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'), 
//                            'order' => 'Subject.subject ASC'));
                
                $this->paginate = array('fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
                'conditions' => array("Subject.tag_ids regexp ('$str_tag_ids')", 'Subject.status' => '1', 'Subject.image !=' => ''),
                'recursive' => 0,
                'order' => 'Subject.subject',
                'limit' => 30);
                $data = $this->paginate('Subject');
                $this->set(compact('data', 'keyword'));
                
            }
            else{
//                $tagsubjects = $this->Subject->find('all', 
//                        array(
//                            'conditions' => array('Subject.status' => '1', 'Subject.image !=' => ''), 
//                            'fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'), 
//                            'order' => 'Subject.subject ASC'));
                
                $this->paginate = array('fields' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
                'conditions' => array('Subject.status' => '1', 'Subject.image !=' => ''), 
                'recursive' => 0,
                'order' => 'Subject.subject',
                'limit' => 30);
                $data = $this->paginate('Subject');
                $this->set(compact('data', 'keyword'));
            }
        }
    }

    function ajax_profile_field_value() {
        if ($_POST) {
            $response = array();
            $subject_id = $_POST['subject_id'];
            $profile_field_id = $_POST['profile_id'];
            $value = trim($_POST['value']);
            $user_id = $_SESSION['Auth']['user']['User']['id'];
            $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`) value('$user_id','$profile_field_id','$value')";
            $result = mysql_query($insert);
            if ($result) {
                $return_html = $this->get_html_profile_field_value($subject_id, $profile_field_id);
                if ($return_html) {
                    $response['error'] = false;
                    $response['data'] = $return_html;
                } else {
                    $response['error'] = true;
                    $response['data'] = false;
                }
            } else {
                $response['error'] = true;
                $response['data'] = false;
            }
            echo (json_encode($response));
            exit;
        } else {
            $response['error'] = true;
            $response['data'] = false;
            echo (json_encode($response));
            exit;
        }
    }

    function get_html_profile_field_value($subject_id = null, $profile_field_value = null) {
        $subject = $this->Subject->find('first', array('conditions' => array('Subject.id' => $subject_id, 'Subject.status' => '1')));
        $user_ids = array_unique(set::classicExtract($subject['SubjectRate'], '{n}.user_id'));
        $profile_data = $this->find_profile_values($user_ids, $subject['Subject']['id']);
        $profile_values = $profile_data['data'];
        $profile_field = null;
        foreach ($profile_values as $profile_value) {
            if ($profile_value['pf']['id'] == $profile_field_value) {
                $profile_field = $profile_value['statistic_data'];
                break;
            }
        }
        $result = '';
        if (is_array($profile_field)) {
            foreach ($profile_field as $value) {
                $percent = number_format(round($value['value_percent'], 1), 1);
                $rating = number_format(round($value['avg_rating'], 1), 1);
                $result .= ucfirst($value['profile_field_value']);
                $result .= "($percent%, UR: $rating)";
                $result .= "<br>";
            }
        }
        return $result;
    }
    
    function _convert_profile_val($profile_field_id, $val){
        $profile_field = $this->ProfileField->find('first', array('conditions' => array('Profilefield.id =' => $profile_field_id)));
        $arr_prof_field = explode(',', $profile_field['ProfileField']['value']);
        return $arr_prof_field[$val-1];
    }

}

?>